package cn.xuqiudong.common.blog.search.service;

import cn.xuqiudong.common.base.model.PageInfo;
import cn.xuqiudong.common.blog.model.BlogArticle;
import cn.xuqiudong.common.blog.search.helper.SearchBlogHelper;
import cn.xuqiudong.common.blog.search.lookup.SearchLookup;
import cn.xuqiudong.common.blog.search.model.SearchBlogArticleModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述:
 *
 * @author Vic.xu
 * @since 2024-06-07 11:45
 */
public class SearchBlogService {

    private final static Logger logger = LoggerFactory.getLogger(SearchBlogService.class);

    private static boolean enable;

    @Value("${search.blog.indexName:articles}")
    private String indexName;

    private final SearchBlogHelper searchHelper;

    public SearchBlogService(SearchBlogHelper searchHelper) {
        this.searchHelper = searchHelper;
        SearchBlogService.enable = searchHelper.isEnable();
    }

    public static boolean isEnable() {
        return enable;
    }

    @PostConstruct
    private void post() {
        logger.info("SearchBlogService initialized ;indexName=[{}]", indexName);
    }

    /**
     * 保存到es
     *
     * @param entity BlogArticle
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void save(BlogArticle entity) {
        if (!enable) {
            return;
        }
        Assert.notNull(entity, "博文不可为空");
        try {
            searchHelper.save(new SearchBlogArticleModel(entity));
        } catch (Exception e) {
            logger.error("保存博文到es出错了", e);
        }
    }

    /**
     * 删除es
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void delete(Integer id) {
        if (!enable) {
            return;
        }
        try {
            searchHelper.delete(String.valueOf(id));
        } catch (Exception e) {
            logger.error("删除博文出错了", e);
        }
    }

    /**
     * 批量删除es
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void deleteBatch(int[] ids) {
        if (!enable) {
            return;
        }
        try {
            List<String> idList = Arrays.stream(ids).boxed().map(String::valueOf).collect(Collectors.toList());
            searchHelper.deleteAll(idList);
        } catch (Exception e) {
            logger.error("批量删除博文出错了", e);
        }
    }

    /**
     * 高亮搜索
     *
     * @param lookup 只包含  page信息和关键词信息的对象
     * @return PageInfo
     * @throws IOException ex
     */
    public PageInfo<SearchBlogArticleModel> search(SearchLookup<SearchBlogArticleModel> lookup) throws IOException {
        if (!enable) {
            return PageInfo.instance(0, Collections.emptyList(), lookup);
        }
        SearchLookup<SearchBlogArticleModel> build = SearchLookup.build("articles", SearchBlogArticleModel.class)
                .keyword(lookup.getKeyword()).page(lookup.getPage(), lookup.getSize())
                //构造高亮字段
                .addHighlightFieldAndSetFunctionString("title", (model, text) -> {
                    model.setTitle(text);
                }).addHighlightFieldAndSetFunctionString("content", (model, text) -> {
                    model.setContent(text);
                }).end();
        return searchHelper.search(build);
    }


}
